package com.coderknock.filter;

import com.coderknock.wrapper.DefinedHttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * <p></p>
 *
 * @author 三产
 * @version 1.0
 * @date 2017-08-26
 * @QQGroup 213732117
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
public class SessionFilter implements Filter {
    protected final Logger logger = LogManager.getLogger(getClass());
    private static final String host = "host";
    private static final String port = "port";
    private static final String seconds = "seconds";

    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("init filterConfig info");
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        //从cookie中获取sessionId，如果此次请求没有sessionId，重写为这次请求设置一个sessionId
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String sid = null;
        if (httpRequest.getCookies() != null) {
            for (Cookie cookie : httpRequest.getCookies()) {
                if (cookie.getName().equals("JSESSIONID")) {
                    sid = cookie.getValue();
                    break;
                }
            }
        }
        if (StringUtils.isEmpty(sid)) {
            try {
                Cookie cookie = new Cookie("JSESSIONID", httpRequest.getLocalAddr() + ":" + request.getLocalPort() + ":" + UUID.randomUUID().toString().replaceAll("-", ""));
                httpResponse.addCookie(cookie);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        logger.info("JSESSIONID:" + sid);
        chain.doFilter(new DefinedHttpServletRequestWrapper(sid, httpRequest, httpResponse), response);
    }

    public void destroy() {
    }

}
